﻿(function ($) {
    $.mini = $.mini || { version: 1.0 };
})(jQuery);
(function ($) {
    //动态加载miniui
    //miniui初始化
    $.mini.init = function () {
        if (window.mini == null) {
            $.ajax({
                url: "/Scripts/miniui/miniui.min.js",
                dataType: 'script',
                async: false
            });
            $.ajax({
                url: "/Scripts/miniui/locale/en_US.js",
                dataType: 'script',
                async: false
            });
        }
        mini.parse("body", true);
        $("#contentbody").show();
    };

    $.mini.message = function (msg, state) {
        //default|success|info|warning|danger
        state = state || "default";
        mini.showTips({
            content: msg,
            state: state,
            x: "center",
            y: "top",
            timeout: 2000
        });
    };

    $.mini.form = {
        save: function (param) {
            if (!param || !param.data) {
                mini.alert("找不到表单", "警告");
                return;
            }
            var messageid = mini.loading("正在保存中，请稍候 ...", "请稍候");
            var data = { dtos: [param.data] };
            $.ajax({
                type: 'POST',
                url: param.url,
                data: data,
                dataType: "JSON",
                success: function (result) {
                    mini.hideMessageBox(messageid);
                    if (result.Type === "Error") {
                        if (typeof param.error == "function") {
                            param.error();
                        }
                        mini.alert(result.Content, "保存出错");
                    } else if (result.Type === "Success") {
                        if (typeof param.success == "function") {
                            param.success();
                        }
                        $.mini.message(result.Content, "success");
                    } else {
                        if (typeof param.error == "function") {
                            param.error();
                        }
                        mini.alert(result.Content, "保存失败");
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (typeof param.error == "function") {
                        param.error();
                    }
                    mini.hideMessageBox(messageid);
                    alert(jqXHR.responseText);
                }
            });
        },
        remove: function (param) {
            if (!param || !param.Id) {
                mini.alert("找不到需要删除的ID", "警告");
                return;
            }
            mini.confirm("确认需要删除吗？", "注意", function (result) {
                if (result === "ok") {
                    $.ajax({
                        type: 'POST',
                        url: param.url,
                        data: { ids: [param.Id] },
                        success: function (result) {
                            if (result.Type === "Error") {
                                if (typeof param.error == "function") {
                                    param.error();
                                }
                                mini.alert(result.Content, "删除数据出错");
                            } else if (result.Type === "Success") {
                                if (typeof param.success == "function") {
                                    param.success();
                                }
                                $.mini.message(result.Content, "success");
                            } else {
                                if (typeof param.error == "function") {
                                    param.error();
                                }
                                mini.alert(result.Content, "删除数据出错");
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert(jqXHR.responseText);
                        }
                    });
                }
            });
        }
    }

    $.mini.grid = function () {
        var config = {
            dataUrl: null,
            addUrl: null,
            deleteUrl: null,
            editUrl: null,
            searchId: null
        };
        var gridParams = {
            allowCellValid: true,
            pageSize: 10,
            idField: "Id",
            sizeList: "[5,10,20,50]"
        };
        var st = this;
        var grid = undefined;

        function beforeLoad(param) {
            if (config.searchId && !param.params.where) {
                var form = new mini.Form("#" + config.searchId);
                var ctls = form.getFields();
                var group = new $.osharp.filter.group();
                for (var i = 0; i < ctls.length; i++) {
                    var x = ctls[i];
                    var field = x.field || x.name;
                    //value没有值，忽略
                    //有unsc这个属性，忽略
                    //没有name或者field属性，忽略
                    if (x.value && !x.unsc && field) {
                        group.Rules.push(new $.osharp.filter.rule(field, x.value, x.op));
                    }
                }

                //$("#" + config.searchId).find("input:hidden,input:text")
                //    .each(function() {
                //        //data-options='{op:"equal",field:"IsDeleted"}'
                //        var $y = $(this);
                //        var options = $y.data("options");
                //        if (options != null && options != "") {
                //            try {
                //                var o = JSON.parse(options);
                //                var f = o.field || o.name;
                //                if (o.value && f) {
                //                    group.Rules.push(new $.osharp.filter.rule(f, o.value, o.op));
                //                }
                //            } catch (e) {

                //            }
                //        }
                //    });
                //console.log(group);

                if (group.Rules.length > 0) {
                    param.params.where = JSON.stringify(group);
                }
            }
        }

        return {
            preInit: function () {

            },
            init: function (opts) {
                opts = opts || {};
                $.extend(config, opts);
                if (config.id == null) {
                    console.log("id为空");
                    return null;
                }

                //先看有没有初始化属性，有则表示从参数中初始化，否则直接从html中初始化
                if (config.params) {
                    grid = new mini.DataGrid();
                    $.extend(gridParams, config.params);
                    grid.set(gridParams);
                } else {
                    grid = mini.get(config.id);
                }

                if (grid == null) {
                    console.log("找不到对象");
                    return null;
                }

                grid.on("beforeload", beforeLoad);

                grid.setUrl(config.dataUrl || config.url);
                return grid;
            },
            load: function () {
                if (config.params) {
                    var el = grid.getEl();
                    $("#" + config.id).html(el);
                } else {
                    grid.load();
                }
            },
            search: function (param) {
                grid.load(param);
            },
            newRow: function (row) {
                row = row || {};
                grid.addRow(row);
                grid.beginEditRow(row);
            },
            editRow: function (uid) {
                var row = grid.getRowByUID(uid);
                if (row) {
                    grid.cancelEdit();
                    grid.beginEditRow(row);
                }
            },
            cancelRow: function () {
                grid.reload();
            },
            restoreRow: function (uid) {
                if (!config.restoreUrl) {
                    console.log("未配置恢复的URL");
                    return;
                }

                var row = grid.getRowByUID(uid);
                if (row) {
                    mini.confirm("确认需要恢复吗？", "注意", function (result) {
                        if (result === "ok") {
                            grid.loading("恢复中，请稍后......");
                            $.ajax({
                                type: 'POST',
                                url: config.restoreUrl,
                                data: { ids: [row.Id] },
                                success: function (result) {
                                    grid.unmask();
                                    if (result.Type === "Error") {
                                        mini.alert(result.Content, "恢复数据出错");
                                    } else if (result.Type === "Success") {
                                        $.mini.message(result.Content, "success");
                                        grid.reload();
                                    } else {
                                        mini.alert(result.Content, "恢复数据出错");
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    grid.unmask();
                                    alert(jqXHR.responseText);
                                }
                            });
                        }
                    });
                }
            },
            deleteRow: function (uid) {
                if (!config.deleteUrl) {
                    console.log("未配置删除的URL");
                    return;
                }

                var row = grid.getRowByUID(uid);
                if (row) {
                    mini.confirm("确认需要删除吗？正式删除将不能还原！", "注意", function (result) {
                        if (result === "ok") {
                            grid.loading("删除中，请稍后......");
                            $.ajax({
                                type: 'POST',
                                url: config.deleteUrl,
                                data: { ids: [row.Id] },
                                success: function (result) {
                                    grid.unmask();
                                    if (result.Type === "Error") {
                                        mini.alert(result.Content, "删除数据出错");
                                    } else if (result.Type === "Success") {
                                        $.mini.message(result.Content, "success");
                                        grid.reload();
                                    } else {
                                        mini.alert(result.Content, "删除数据出错");
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    grid.unmask();
                                    alert(jqXHR.responseText);
                                }
                            });
                        }
                    });
                }
            },
            recycleRow: function (uid) {
                if (!config.recycleUrl) {
                    console.log("未配置回收的URL");
                    return;
                }

                var row = grid.getRowByUID(uid);
                if (row) {
                    mini.confirm("确认需要回收吗？", "注意", function (result) {
                        if (result === "ok") {
                            grid.loading("回收中，请稍后......");
                            $.ajax({
                                type: 'POST',
                                url: config.recycleUrl,
                                data: { ids: [row.Id] },
                                success: function (result) {
                                    grid.unmask();
                                    if (result.Type === "Error") {
                                        mini.alert(result.Content, "回收数据出错");
                                    } else if (result.Type === "Success") {
                                        $.mini.message(result.Content, "success");
                                        grid.reload();
                                    } else {
                                        mini.alert(result.Content, "回收数据出错");
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    grid.unmask();
                                    alert(jqXHR.responseText);
                                }
                            });
                        }
                    });
                }
            },
            updateRow: function () {
                var enable = grid.getEnabled();
                if (!enable) {
                    return;
                }

                grid.commitEdit();

                grid.loading("保存中，请稍后......");
                var addList = grid.getChanges("added");
                if (addList && addList.length > 0) {
                    $.ajax({
                        type: 'POST',
                        url: config.addUrl,
                        data: { dtos: addList },
                        dataType: "JSON",
                        success: function (result) {
                            grid.unmask();
                            if (result.Type === "Error") {
                                mini.alert(result.Content, "新增数据出错");
                            } else if (result.Type === "Success") {
                                $.mini.message(result.Content, "success");
                                grid.reload();
                            } else {
                                mini.alert(result.Content, "新增数据出错");
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            grid.unmask();
                            alert(jqXHR.responseText);
                        }
                    });
                }

                var editList = grid.getChanges("modified");
                if (editList && editList.length > 0) {
                    $.ajax({
                        type: 'POST',
                        url: config.editUrl,
                        data: { dtos: editList },
                        dataType: "JSON",
                        success: function (result) {
                            grid.unmask();
                            if (result.Type === "Error") {
                                mini.alert(result.Content, "更新出错");
                            } else if (result.Type === "Success") {
                                $.mini.message(result.Content, "success");
                                grid.reload();
                            } else {
                                mini.alert(result.Content, "更新数据出错");
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            grid.unmask();
                            alert(jqXHR.responseText);
                        }
                    });
                }
                grid.unmask();

                //var deleteList = grid.getChanges("removed");
            }
        }
    }
})(jQuery);